import Taro from "@tarojs/taro";

const initialState = {
  carList: Taro.getStorageSync('carList') || []
}
export default function reducer(state = initialState, { type, payload }) {
  switch (type) {
    case 'ADD_CAR':
      const item = state.carList.find(item => item.id === payload.id)
      if (item) {
        item.count++;
      } else {
        state.carList.unshift({ ...payload, count: 1 })
      }
      break;
    case 'DELETE_CAR':

      break;
    case 'CHANGE_COUNT':
      // 0 - 减 、1 - 加
      const { id, actionType } = payload;
      state.carList = state.carList.map(item => {
        if (item.id === id) {
          return {
            ...item,
            count: actionType ? item.count + 1 : item.count - 1
          }
        }
        return item
      })
      break;
    case 'CHECK_ITEM':
      const itemInfo = state.carList.find(item => item.id === payload.id);
      if (itemInfo) {
        itemInfo.checked = payload.checked
      }
      break;
    case 'CHECK_ALL':
      state.carList.forEach(item => {
        item.checked = payload.checked
      })
      break
  }
  Taro.setStorageSync('carList', state.carList)
  return JSON.parse(JSON.stringify(state))
}